package com.bjpowernode.handlers;

import com.bjpowernode.result.Result;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class MyExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public Result handleException(Exception e) {
        e.printStackTrace();
        return Result.FAIL(e.getMessage());
    }

    @ExceptionHandler(value = DataIntegrityViolationException.class)
    public Result handleException(DataIntegrityViolationException e) {
        e.printStackTrace();
        return Result.FAIL("您要删除的内容存在尚未解除的关联数据", "数据库外键约束失败");
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handlerBusinessException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        StringBuilder stringBuilder = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(globalError -> stringBuilder.append(globalError.getDefaultMessage()).append(";"));
        return Result.FAIL(stringBuilder.toString());
    }
}

